package com.oss.robot;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.lang.StringUtils;

import com.oss.PMF;
import com.oss.model.Link;
import com.oss.model.Project;
import com.oss.model.Topic;
import com.oss.service.system.CacheService;

/**
 * 用于将Link进行归类的机器人
 * 
 * @author xueqiang.mi
 * @since 2010-7-21
 */
public class ClassfyRobot extends BaseRobot {

	static public final String NAME = "ClassfyRobot";

	static public final Integer TASK_NUMBER_PER_TIME = 100;

	@SuppressWarnings("unchecked")
	public void doClassfy() {
		// 从数据库里取出N个未进行归类的Link
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			query.setFilter("prj == 'notSet' || prj == 'unClassfied'");
			query.setRange(0, TASK_NUMBER_PER_TIME);
			Collection<Link> lnks = (Collection<Link>) query.execute();

			for (Link lnk : lnks) {
				// 分析Link的Title进行项目归类
				String title = lnk.getName();
				List<Project> prjs = CacheService.getPrjs();
				for (Project prj : prjs) {
					if (StringUtils.containsIgnoreCase(title, prj.getName())) {
						lnk.setPrj(prj.getId());
						break;
					}
				}

				// 分析Link的Title进行Topic归类
				List<Topic> topics = CacheService.getTopics();
				for (Topic t : topics) {
					if (StringUtils.containsIgnoreCase(title, t.getName())) {
						lnk.setTopic(t.getId());
						break;
					}
				}
			}
		} finally {
			pm.close();
		}
	}
}
